package com.example.musicbox.utils;
import com.example.musicbox.config.MyException;
import com.example.musicbox.entity.dto.UserDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author : zhy
 * @since : 2022/8/1
 * 这个类用于生成token
 */
@Component
public class GeneratorToken {

    @Value("${redisConf.expire}")
    private Integer expireTime;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 生成用户token
     * @param userDto
     * @return
     */
    public String getToken(UserDto userDto)
    {
        BASE64Encoder encoder = new BASE64Encoder();
        String token =DigestUtils.md5DigestAsHex(
                (
                        DigestUtils.md5DigestAsHex((userDto.getUId()+"xieyucan"+userDto.getUserName()+new Date()).getBytes())
                        +"$"
                        +encoder.encode((userDto.getUPhoto()+new Date()).getBytes())
                        ).getBytes()
        );
        saveTokenInRedis(token, userDto.getUId());
        return token;
    }

    /**
     * 将token存放到redis中
     * @param token
     * @param userId
     */
    private void saveTokenInRedis(String token,Integer userId)
    {
        try {
            redisTemplate.opsForValue().set(token,userId, expireTime,TimeUnit.HOURS);
        }catch (Exception e){
            throw new RuntimeException("token存储失败");
        }
    }


    /**
     * 根据token在redis获取用户的id
     * @param token
     * @return
     */
    public Integer getUserId(String token)
    {
        try {
            Integer userId = (Integer) redisTemplate.opsForValue().get(token);
            return userId;
        }catch (Exception e){
            throw new MyException("用户登录超时");
        }

    }

}
